#include "MidNightMap.h"
#include <QDebug>
#include <osgEarth/TerrainEngineNode>

using namespace osgEarth;

MidNightMap::MidNightMap()
{
    _mapNode = 0;
    _terrainVP = 0;
}

void MidNightMap::setEnable(bool b)
{
    if(!_mapNode) return;
    if(b){
        if(!_terrainVP){

            osgEarth::MapNode* mn = _mapNode;
            osg::StateSet* tss = mn->getTerrainEngine()->getSurfaceStateSet();
            VirtualProgram* vp = VirtualProgram::getOrCreate(tss);
            _terrainVP = vp;

//            int cid = _mapNode->getMap()->getImageLayerAt(0)->getUID();
//            qDebug() << cid;

//            osg::Uniform* u = new osg::Uniform(osg::Uniform::INT, "lid");
//            u->set(cid);

            //mn->getOrCreateStateSet()->addUniform(u);
        }
//        const char* vertShader1 =
//            "#version " GLSL_VERSION_STR "\n"
//            "out float fogfactor;"
//            "in vec4 oe_terrain_attr;"
//            "uniform vec4 oe_tile_key;"
//            "uniform float u_userfog; \n"
//            "void make_it_red_vert(inout vec4 vert) {\n"
//            "   float height = oe_terrain_attr[3];"
//            "   height = (height - 200.0) / 1800.0;"
//            "   fogfactor = clamp(height,0.05,1.0);"
//            "   fogfactor = min(fogfactor,u_userfog);"
//            "   fogfactor = oe_tile_key.z < 7 ? 1.0:fogfactor;"
//            "}\n";

        const char* fragShader1 =
            "#version " GLSL_VERSION_STR "\n"
            "void make_it_cool(inout vec4 color) {\n"
            "    float r=color.r;\n"
            "    float g=color.g;\n"
            "    float b=color.b;\n"
            "    r =  min(abs(r - 0.917),abs(r - 0.639));\n"
            "    float b2 =  abs(b - 230.0/255.0);\n"
            "    g =  abs(g - 230.0/255.0);\n"
            "    g = g*1.5;\n"
            "    r = r*1.5;\n"
            "    b = b2*1.5;\n"
            "    color = vec4(r,g,b,1.0);\n"
            "}\n";

        //const char* fragShader1 =
        //    "#version " GLSL_VERSION_STR "\n"
        //    "void make_it_cool(inout vec4 color) {\n"
        //    "    float r=color.r;\n"
        //    "    float g=color.g;\n"
        //    "    float b=color.b;\n"
        //    "    r = 1.0 - r;\n"
        //    "    b = 1.0 - b;\n"
        //    "    g = 1.0 - g;\n"
        //    "    color = vec4(b,g-0.1,r-0.2,1.0);\n"
        //    "}\n";
        //_terrainVP->setFunction("make_it_red_vert", vertShader1, osgEarth::ShaderComp::LOCATION_VERTEX_VIEW);
        _terrainVP->setFunction("make_it_cool", fragShader1, osgEarth::ShaderComp::LOCATION_FRAGMENT_LIGHTING);

    }else{
        if(_terrainVP){
            //_terrainVP->removeShader("make_it_red_vert");
            _terrainVP->removeShader("make_it_cool");
        }
    }
}

void MidNightMap::close()
{
    this->setEnable(false);
}

